/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.zx.common.utils;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 *
 * @author Mark sunlightcs@gmail.com
 */
@Component
public class RedisUtils {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private ValueOperations<String, String> valueOperations;
    @Autowired
    private HashOperations<String, String, Object> hashOperations;
    @Autowired
    private ListOperations<String, Object> listOperations;
    @Autowired
    private SetOperations<String, Object> setOperations;
    @Autowired
    private ZSetOperations<String, Object> zSetOperations;

    /**
     * 用于不同的项目共用一个redis 服务器 方便管理，不会重名
     */
    private static final String PROJECT_PREFIX = "evaluation:";

    /**  默认过期时长，单位：秒 */
    public final static long DEFAULT_EXPIRE = 60 * 60 * 24;
    /**
     * 过期时间 单位是秒 TimeUnit.SECONDS
     */
    public enum expireSet {
        /**
         *  2小时  60*60*2
         */
        TWOHOUR(7200),

        /**
         * 12 小时  60*60*12
         */
        TWELVEHOUR(43200),

        /**
         * 一天 24 小时 60*60*24
         */
        ONEDAY(86400),

        /**
         * 一周 24*7
         */
        ONEWEEK(604800);

        private int value;

        expireSet(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }
    /**
     * role_perms_ 某一角色下权限集合
     * redis key 前缀
     */
    public enum keyPrefix {
        user_token_, user_, user_login_,users_, members_,config_,user_authorization_info_,
        role_, perm_, roles_, role_perms_str_, role_perms_int_, role_perms_menus_, role_perms_, perms_,
        eval_report_dimension
    }
    /**  不设置过期时长 */
    public final static long NOT_EXPIRE = -1;
    private final static Gson gson = new Gson();

    public void set(String key, Object value, long expire){
        valueOperations.set(PROJECT_PREFIX+key, toJson(value));
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
    }

    public void set(String key, Object value){
        set(key, value, DEFAULT_EXPIRE);
    }

    public <T> T get(String key, Class<T> clazz, long expire) {
        String value = valueOperations.get(PROJECT_PREFIX+key);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(key, expire, TimeUnit.SECONDS);
        }
        return value == null ? null : fromJson(value, clazz);
    }

    public <T> T get(String key, Class<T> clazz) {
        return get(key, clazz, NOT_EXPIRE);
    }

    public String get(String key, long expire) {
        String value = valueOperations.get(PROJECT_PREFIX+key);
        if(expire != NOT_EXPIRE){
            redisTemplate.expire(PROJECT_PREFIX+key, expire, TimeUnit.SECONDS);
        }
        return value;
    }

    public String get(String key) {
        return get(key, NOT_EXPIRE);
    }
    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key){

        String value = valueOperations.get(PROJECT_PREFIX+key);
        if(StringUtils.isEmpty(value)){
            return false;
        }else {
            return true;
        }
    }
    public void delete(String key) {
        redisTemplate.delete(PROJECT_PREFIX+key);
    }

    public void deleteBatch(String keyPrefix,Long[] ids){
        for (Long l : ids){
            this.delete(keyPrefix+l.toString());
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String ... key){
        if(key!=null && key.length>0){
            if(key.length==1){
                redisTemplate.delete(PROJECT_PREFIX+key[0]);
            }else{
                redisTemplate.delete(CollectionUtils.arrayToList(PROJECT_PREFIX+key));
            }
        }
    }

    /**
     * 删除前缀一样的缓存
     * @param key
     */
    public  void delPrefix(String key){
        Set<String> set = redisTemplate.keys(PROJECT_PREFIX+key+"*");
        Iterator<String> it = set.iterator();
        while(it.hasNext()){
            String keyStr = it.next();
            System.out.println(keyStr);
            this.del(keyStr);
        }
    }
    /**
     * Object转成JSON数据
     */
    private String toJson(Object object){
        if(object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String){
            return String.valueOf(object);
        }
        return gson.toJson(object);
    }

    /**
     * JSON数据，转成Object
     */
    private <T> T fromJson(String json, Class<T> clazz){
        return gson.fromJson(json, clazz);
    }
}
